# -*- coding: utf-8 -*-

from datetime import *

import time
import Cookie
import random

from google.appengine.ext import db  
from google.appengine.api import users
from google.appengine.api import urlfetch

from django.http import HttpResponse
from django.utils.html import escape
from django.shortcuts import render_to_response
from appengine_utilities.sessions import Session
from appengine_utilities.flash import Flash

from templates import templatesfile
from settings import *
from ccutils import *
from xmsmodels import *
from zipme import *
from views import __checkGroupAuth__
from language import _T_

        
def login(request):
    session = Session()
    session.delete()
    return HttpResponseRedirect(sys_loginurl)
    
def logout(request):
    session = Session()
    session.delete()
    return HttpResponseRedirect(sys_logouturl)

#@check_current_user_and_group_admin 
def groupaction(request,action,key,email):
    session = Session()
    flash = Flash()
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup', None))
    lang = curUser.Language
    
    if action == "quitgroup":
        key = unicode(key,'utf-8')
        group = XMSGroup.GetActivedGroupByName(key)
        if not __checkGroupAuth__(curUser,group,'user'):
            flash.msg = _T_('no_auth',)
            return HttpResponseRedirect("/")
        if curUser.IsOwnerOfGroup(group):
            flash.msg = _T_('owner_cannot_quit',lang)
            return HttpResponseRedirect("/allgroups")
        
        if curUser.IsAdminOfGroup(group):
            group.Admin2User(curUser)
        
        group.DeleteUser(curUser)
        flash.msg = _T_('quit_group',lang) % group.GroupName
        return HttpResponseRedirect("/allgroups")
        pass
    
    if not __checkGroupAuth__(curUser,curGroup,'admin'):
        flash.msg = _T_('no_auth',lang)
        return HttpResponseRedirect("/")
    
    if action == "delincome":
        XMSIncome.delete(XMSIncome.get(key))
        pass
    
    elif action == "delpayout":
        XMSPayout.delete(XMSPayout.get(key))
        pass
    
    elif action == "delgroup":
        if curUser.IsOwnerOfGroup(curGroup):
            curGroup.Actived = False
            curGroup.save()
            session['CurrentGroup'] == None
        pass
    
    elif action == "delawaitinguser":
        curGroup.DeleteAwaitingUser(email)
        session['CurrentGroup'] == curGroup.GroupName
        return HttpResponseRedirect("/awaiting")
        pass
    
    elif action == "deluser":
        key = unicode(key,'utf-8')
        user = XMSUser.GetXMSUserByNickName(key)
        if user.Actived and user.IsUserOfGroup(curGroup):
            curGroup.DeleteUser(user)
            flash.msg = _T_('user_deleted',lang) % user.NickName
        return HttpResponseRedirect("/groupusers")
        pass
    
    elif action == "admin2user":
        if not __checkGroupAuth__(curUser,curGroup,'owner'):          
            flash.msg = _T_('no_owner',lang)
            return HttpResponseRedirect("/")
        key = unicode(key,'utf-8')
        user = XMSUser.GetXMSUserByNickName(key)
        if user.Actived and user.IsAdminOfGroup(curGroup):    
            curGroup.Admin2User(user)
            flash.msg = _T_('admin_degraded',lang) % user.NickName
        return HttpResponseRedirect("/groupadmins")
        pass
    
    elif action == "user2admin":
        key = unicode(key,'utf-8')
        user = XMSUser.GetXMSUserByNickName(key)
        if user.Actived and user.IsUserOfGroup(curGroup):
            curGroup.User2Admin(user)
            flash.msg = _T_('user_upgraded',lang) % user.NickName
        return HttpResponseRedirect("/groupusers")
        pass
    
    elif action == "user2owner":
        if not __checkGroupAuth__(curUser,curGroup,'owner'):
            flash.msg = _T_('no_owner',lang)
            return HttpResponseRedirect("/")
        pass
        
    return HttpResponseRedirect("/summary")
    
#@check_current_user_and_group_admin 
def awaiting(request):
    session = Session()
    flash = Flash()
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))
    if not __checkGroupAuth__(curUser,curGroup,'admin'):
        flash.msg = _T_('no_auth',curUser.Language)
        return HttpResponseRedirect("/")
    if request.POST:
        li = []
        for key in request.POST.getlist('await'):
            li.append(key)
        xmsusers = XMSUser.get(li)
        for user in xmsusers:
            if user.Actived:
                curGroup.ApproveAwaitingUser(user)
            session['CurrentGroup'] = curGroup.GroupName
            return HttpResponseRedirect('/awaiting')
    try:
        page_index=int (request.GET['page'])
    except:
        page_index=1
    
    entries,links=Pager(query=curGroup.GetAwaitingQuery(),items_per_page=PAGER_ITEMS_PER_PAGE , \
                        pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
    
    awaiting = {'count': links['count'], 'list':entries}        
                             
    return render_to_response(templatesfile[curUser.Language]['awaiting'],{'curUser': curUser,'curGroup':curGroup,
                                    'awaiting': awaiting,'show_awaiting':True,
                                    'pager':links, 'flash':flash,
                                    'isAdmin':True,})
 
def groupusers(request):
    session = Session()
    flash = Flash()
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))
    if not __checkGroupAuth__(curUser,curGroup,'admin'):
        flash.msg = _T_('no_auth',curUser.Language)
        return HttpResponseRedirect("/")

    try:
        page_index=int (request.GET['page'])
    except:
        page_index=1

    entries,links=Pager(query=curGroup.GetUsersQueryByAuth('user'),items_per_page=PAGER_ITEMS_PER_PAGE , \
                        pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
    
    groupusers = {'count': links['count'], 'list':entries}        
                             
    return render_to_response(templatesfile[curUser.Language]['groupusers'],{'curUser': curUser,'curGroup':curGroup,
                                    'groupusers': groupusers,'show_users':True,
                                    'pager':links, 'flash':flash,
                                    'isAdmin':curUser.IsAdminOfGroup(curGroup),}) 

def groupadmins(request):
    session = Session()
    flash = Flash()
    curUser = session.get('CurrentUser', None)
    curGroup = XMSGroup.GetActivedGroupByName(session.get('CurrentGroup',None))
    if not __checkGroupAuth__(curUser,curGroup,'admin'):
        flash.msg = _T_('no_auth',curUser.Language)
        return HttpResponseRedirect("/")

    try:
        page_index=int (request.GET['page'])
    except:
        page_index=1

    entries,links=Pager(query=curGroup.GetUsersQueryByAuth('admin'),items_per_page=PAGER_ITEMS_PER_PAGE , \
                        pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
    
    groupusers = {'count': links['count'], 'list':entries}        
                             
    return render_to_response(templatesfile[curUser.Language]['groupusers'],{'curUser': curUser,'curGroup':curGroup,
                                    'groupusers': groupusers,'show_admins':True,
                                    'pager':links, 'flash':flash,
                                    'isAdmin':curUser.IsAdminOfGroup(curGroup),
                                    'isOwner':curGroup.IsOwner(curUser),}) 
        
@check_current_user 
def profile(request):
    session = Session()
    curUser = session['CurrentUser']
    
    flash = Flash()
    if request.POST:
        email = unicode(escape(request.POST['email']),'utf-8').strip()
        nickname = unicode(escape(request.POST['nickname']),'utf-8').strip()
        intro = unicode(escape(request.POST['intro']),'utf-8').strip()
        lang = unicode(escape(request.POST['lang']),'utf-8').strip()
        curUser.Intro = intro
        curUser.Language = lang
        curUser.save()
        session['CurrentUser'] = curUser
        flash.msg = _T_('user_info_updated',lang) %(nickname)
        return HttpResponseRedirect("/profile")
    
    lang = curUser.Language      
    return render_to_response(templatesfile[lang]['join'], {'curUser': curUser,
                            'disable_name': True, 'nomenu':True,
                            'flash':flash,'action':'profile',
                            'legendname':_T_('profile',lang), 'lang':lang ,
                            'email':curUser.User.email(),
                            'nickname': curUser.NickName,
                            'intro':curUser.Intro,
                            'submit':_T_('save',lang),})
    
@check_current_user        
def creategroup(request):
    session = Session()
    curUser = session['CurrentUser']
    flash = Flash()
    
    lang = curUser.Language
    if request.POST:
        Description = unicode(escape(request.POST['Description']),'utf-8').strip()
        GroupName = unicode(escape(request.POST['GroupName']),'utf-8').strip()
        Privated = bool(escape(request.POST['Privated']) == 'true')
        
        if XMSGroup.CheckGroupExist(GroupName):
            flash.msg = _T_('group_rename',lang) %(GroupName)
            return HttpResponseRedirect("/creategroup")
        else:
            xmsgroup = XMSGroup.get_or_insert(u"GroupName:"+GroupName, GroupName = GroupName)
            xmsgroup.Description = Description
            xmsgroup.Actived = True
            xmsgroup.Privated = Privated
            xmsgroup.Owner = curUser
            xmsgroup.put()
            flash.msg = _T_('group_created',lang) %{'groupname':GroupName,
                                                    'username':curUser.NickName,}
            session['CurrentGroup'] = xmsgroup.GroupName
            return HttpResponseRedirect("/summary")
        
    context = {'curUser': curUser,
               'flash':flash,'submit':_T_('create_group',lang),
               'nomenu': True, }
    return render_to_response(templatesfile[lang]['creategroup'],context)

@requires_login        
def join(request):
    googleuser = users.get_current_user()
    xmsuser = XMSUser.GetXMSUserByUser(googleuser)
    flash = Flash()
    if xmsuser:   #email already in XMSUser
        lang = xmsuser.Language
        flash.msg = _T_('user_exist',lang) %(users.get_current_user().email())
        return HttpResponseRedirect("/")
    if request.POST:
        email = unicode(escape(request.POST['email']),'utf-8').strip()
        nickname = unicode(escape(request.POST['nickname']),'utf-8').strip()
        intro = unicode(escape(request.POST['intro']),'utf-8').strip()
        lang = unicode(escape(request.POST['lang']),'utf-8').strip()
        if email != googleuser.email():
            return HttpResponseRedirect("/logout")
        
        if XMSUser.CheckUserExist(nickname,googleuser):
            # nickname already in database
            flash.msg = _T_('user_rename',lang) %(nickname)
            return HttpResponseRedirect("/join")
        else:
            #create new XMS user
            xmsuser = XMSUser.get_or_insert("UserName:"+nickname, NickName = nickname, User = googleuser)
            xmsuser.Intro = intro
            xmsuser.Actived = True
            xmsuser.Language = lang
            xmsuser.put()
            flash.msg = _T_('welcome_newuser',lang) %(nickname)
            return HttpResponseRedirect("/")
    
    session = Session()
    lang = session['lang']
        
    context = {'nomenu': True,'email':googleuser.email(),
               'nickname':googleuser.nickname(),
               'intro':'','action':'join', 
               'submit':_T_('join_now',lang), 'lang':lang,
               'flash':flash, }
    
    return render_to_response(templatesfile[lang]['join'],context)

@requires_login
def joingroup(request):
    session = Session()
    curUser = session.get('CurrentUser',None)
    flash = Flash()
    if not curUser:   #email already in XMSUser
        lang = session.get('lang', 'en-us')
        flash.msg = _T_('pls_join',lang)
        return HttpResponseRedirect("/")
    else:
        lang = curUser.Language
        
    if request.POST:
        pass
    
    try:
        groupname=escape(request.GET['groupname'])
    except:
        groupname=None
        
    if groupname:
        try:
            groupname = unicode(groupname, 'utf-8')
            xmsgroup = XMSGroup.GetGroupByName(groupname)
            
            if curUser.IsUserOfGroup(xmsgroup):
                flash.msg = _T_('already_in_group',lang) % (groupname)
                return HttpResponseRedirect("/joingroup")
            else:
                if curUser.User in xmsgroup.AWaitingJoinUser:
                    flash.msg = _T_('already_in_awaiting',lang) % (groupname)
                    return HttpResponseRedirect("/joingroup")
                if xmsgroup.Actived and not xmsgroup.Privated:
                    curUser.JoinGroup(xmsgroup)
                    flash.msg = _T_('awaiting',lang) % groupname
                    return HttpResponseRedirect("/joingroup")
        except:
            flash.msg = _T_('error_join_group',lang) % (groupname)
            return HttpResponseRedirect("/joingroup")
    
    try:
        page_index=int(request.GET['page'])
    except:
        page_index=1
    
    grouplist = XMSGroup.GetPublicGroups()
    entries,links=Pager(query=grouplist,items_per_page=PAGER_ITEMS_PER_PAGE,pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
         
    context = {'nomenu': True,
               'pager':links, 'grouplist': entries,
               'curUser': curUser,
               'flash':flash,
               'joingroup':True, }
    return render_to_response(templatesfile[lang]['grouplist'],context)

@requires_login
def allgroups(request):
    session = Session()
    curUser = session.get('CurrentUser',None)
    flash = Flash()
    if not curUser:   #email already in XMSUser
        lang = session.get('lang', 'en-us')
        flash.msg = _T_('pls_join',lang)
        return HttpResponseRedirect("/join")
    if request.POST:
        pass
    
    try:
        page_index=int(request.GET['page'])
    except:
        page_index=1
    
    allgroup = curUser.GetAllGroupsQuery()
    entries,links=Pager(query=allgroup,items_per_page=PAGER_ITEMS_PER_PAGE,pages_follow = PAGER_PAGES_FOLLOW ).fetch(page_index)
         
    context = {'nomenu': True,
               'pager':links, 'grouplist': entries,
               'curUser': curUser,
               'flash':flash, 'allgroups':True,}
    return render_to_response(templatesfile[curUser.Language]['grouplist'],context)   
    


@check_current_user_and_group
def genReport(request,chart,report,count,width,height):
    count = int(count)
    width = int(width)
    height = int(height)
    
    size = (width,height)
    imagepath = XMSReport.GetReportPath(chart,\
                                         report, count, \
                                         title="报表", size=size)
    
    
    
    
    chart = XMSChart.GetChart(imagepath)
    if not chart:
        result = urlfetch.fetch(imagepath)
        if result.status_code == 200:
            chart = XMSChart.SaveChart(imagepath,result.headers['Content-Type'],result.content)
        else:
            return HttpResponseNotFound()
    
    resp = HttpResponse()
    resp.headers['Content-Type'] = chart.ContentType
    resp.write(chart.Data)  
    return resp
 
@requires_site_admin
def downloadscodes(request):
    resp = HttpResponse()
    if users.is_current_user_admin():
        folder = os.path.dirname(__file__)
        resp.headers['Content-Type'] = 'application/zip'
        resp.headers['Content-Disposition'] = 'attachment; filename="%s.zip"' % os.path.basename(folder)
        fid=createZip(folder)
        while True:
            buf=fid.read(2048)
            if buf=="": break
            resp.write(buf)
        fid.close()  
    else:
        resp.headers['Content-Type'] = 'text/html'
        resp.write("<a href=\"%s\">You must be admin</a>." %loginurl)
    return resp
